/*
 * OpcionsServlet.java
 *
 * Created on 11 de enero de 2008, 16:09
 */

package org.wooxes.server;

import java.io.*;
import java.net.*;

import javax.servlet.*;
import javax.servlet.http.*;

import java.sql.*;

/**
 *
 * @author woox
 * @version
 */
public class OpcionsServlet extends HttpServlet {
    
    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
               
        String nom=request.getParameter("nom");
        String valor=request.getParameter("valor");
        
        valor = valor.replace("\\","\\\\");

        // Es comprova, si és necessari, si es tracta de un valor numèric.
        
        if(nom.equals("maxfilesize")){
            if(!isNumeric(valor)){
                out.println("Error: Es necessita un valor numèric");
                return;
            }
        }
        
        else if(nom.equals("uploaddir")){
            File dir = new File(valor);
            if( !dir.exists() || dir.isFile() ){
                out.println("Error: Directori no vàlid");
                return;
            }
        }
        
        // Obrir connexió amb bd
        ConnexioSQL connexio = new ConnexioSQL();
        Connection conn = connexio.getConnection();
        
        try{
            Statement statement = conn.createStatement();
            int modificats = statement.executeUpdate("UPDATE configuracio set valor='"+valor+"' WHERE nom='"+nom+"'");
            statement.close();
            // Comprovació resultat
            if(modificats != 1){
                System.out.println("Error: Massa coincidencies");
                return;
            }
        }
        catch(Exception e){
            System.out.println(e);
        }
        
        out.println("ok:"+valor);
        out.close();
    }

    private boolean isNumeric(String cadena){
	try {
		Integer.parseInt(cadena);
		return true;
	} catch (NumberFormatException nfe){
		return false;
	}
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    
    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>
}
